package my.springboot.jpa;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 类描述: 通用数据库操作类
 * 创建人: 闵楠  
 * 创建时间: 2017-5-25 下午05:51:49
 */
public class CommonDao {

	@Autowired
	@PersistenceContext
	private EntityManager entityManager;
	
	
	/**
	 * 执行原生sql
	 * @param <T>
	 * @param sql
	 * @param resultClass
	 */
	public <T> List<T> executeNativeSql(String sql, Class<T> resultClass) {
		return entityManager.createNativeQuery(sql, resultClass).getResultList();
	}
	
	/**
	 * 执行原生sql,并转为特定对象
	 * @param <T>
	 * @param sql
	 * @param resultClass
	 */
	public <T> List<T> executeNativeSqlTransform(String sql, Class<T> resultClass) {
		//执行原生SQL
		Query nativeQuery = entityManager.createNativeQuery(sql);
		//指定返回对象类型
		nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean( resultClass ));
		
		//返回对象
		List<T> resultList = nativeQuery.getResultList();       
		
		return resultList;
	}
	/**
	 * 根据条件执行sql查询
	 * @param <T>
	 * @param tableName
	 * @param sqlConditions
	 * @param domainClass
	 */
	public <T> List<T> getDomainDoByCondition(String sql, Class<T> resultClass,Map<String,Object> params) {
		//执行原生SQL
		Query nativeQuery = entityManager.createNativeQuery(sql);
		for (String key : params.keySet()) {
			nativeQuery.setParameter(key, params.get(key));
		}
		//指定返回对象类型
		nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean( resultClass ));
		
		//返回对象
		List<T> resultList = nativeQuery.getResultList();       
		
		return resultList;
	}
	
	
}
